import { useEffect } from "react";
import { useReactive } from "ahooks";
import localforage from "localforage";
import { useModel } from "umi";
import { useOrganization } from "@share-code/public";

import appInfo from "../../publish/app.js";

import { OrganizationBaseInformationByUuid } from "../_graphql/organizations";

export default function organizationModal() {
    const { remoteData, graphqlFetchPlatform } = useModel("global");
    const { loginInfo } = useModel("person.info");
    const { loadLocalOrganizationInfo, loadRemoteOrganizationInfo } = useOrganization(remoteData);

    let state = useReactive({
        currentOrganizationUuid: "",
        currentOrganizationFullName: "",
        currentOrganizationInfo: {},
        organizationInfo: {},
        remoteOrganizationInfo: {},
    });

    const initData = async () => {
        state.currentOrganizationUuid = await localforage.getItem(appInfo.appUuid + "-当前组织");
        state.currentOrganizationFullName = await localforage.getItem(appInfo.appUuid + "-当前组织名称");
    };

    useEffect(() => {
        initData();
    }, []);

    const loadData = async () => {
        let remoteOrganizationInfo = {};
        let organizationInfo = await loadLocalOrganizationInfo(window.organizationUuid);
        loginInfo?.authCenterUrl && (remoteOrganizationInfo = await loadRemoteOrganizationInfo(loginInfo.authCenterUrl, window.organizationUuid));
        setOrganizationStateValue({ organizationInfo, remoteOrganizationInfo });
    };

    useEffect(() => {
        loadData();
    }, [loginInfo]);

    const loadCurrentOrganizationBaseInfo = async () => {
        let res = await graphqlFetchPlatform({
            query: OrganizationBaseInformationByUuid,
            variables: { uuid: state.currentOrganizationUuid },
        });
        state.currentOrganizationInfo = res?.a || {};
    };

    useEffect(() => {
        state.currentOrganizationUuid && loadCurrentOrganizationBaseInfo();
    }, [state.currentOrganizationUuid]);

    const setOrganizationStateValue = (obj) => {
        for (let key in obj) {
            state[key] = obj[key];
        }
    };

    const setCurrentOrganizationUuid = (uuid, fullName) => {
        state.currentOrganizationUuid = uuid;
        state.currentOrganizationFullName = fullName;
        localforage.setItem(appInfo.appUuid + "-当前组织", uuid);
        localforage.setItem(appInfo.appUuid + "-当前组织名称", fullName);
    };

    return {
        organizationUuid: window.organizationUuid,
        ...state,
        setOrganizationStateValue,
        setCurrentOrganizationUuid,
        loadCurrentOrganizationBaseInfo,
    };
}
